from flask import Flask, request, jsonify
import os
import subprocess

app = Flask(__name__)

# 同时支持 GET 和 POST
@app.route('/play', methods=['GET', 'POST'])
def play_voice():
    if request.method == 'GET':
        voice_type = request.args.get('type', 'success')
    else:
        voice_type = request.json.get('type', 'success')

    voice_file = f"E:/shengyi/qiandao/ThinkAdmin/tools/device_tcp/voice/checkin_{voice_type}.mp3"

    print(f"Attempting to play: {voice_file}")

    if os.path.exists(voice_file):
        try:
            # 方法1：使用 Windows Media Player
            os.system(f'start wmplayer "{voice_file}" /play /close')
            # 或者方法2：使用 PowerShell（如果上面不行）
            # os.system(f'powershell -c "(New-Object Media.SoundPlayer \'{voice_file}\').PlaySync()"')

            return jsonify({'status': 'success', 'file': voice_file})
        except Exception as e:
            return jsonify({'status': 'error', 'message': str(e)})
    else:
        return jsonify({'status': 'file_not_found', 'file': voice_file})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)